package com.xxh.kfc.controller;

import com.xxh.kfc.dao.FoodDao;
import com.xxh.kfc.dao.TypeDao;
import com.xxh.kfc.entity.Food;

import com.xxh.kfc.entity.Type;
import com.xxh.kfc.entity.User;
import com.xxh.kfc.service.OrderService;
import com.xxh.kfc.service.impl.OrderServiceImpl;
import com.xxh.kfc.utils.MyBatisUtils;
import org.apache.ibatis.session.SqlSession;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@WebServlet(name = "FoodServlet",urlPatterns = "/food/*")
public class FoodServlet extends HttpServlet {
    SqlSession sqlSession=null;
    //临时保存购物车信息
    List<Food> carlist = new ArrayList<>();



    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request,response);
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //拿到session
        HttpSession session = request.getSession();

        //拿到sqlsession
        sqlSession = MyBatisUtils.getSqlSession();
        //获取mapper
        TypeDao typeDao = sqlSession.getMapper(TypeDao.class);
        String pathInfo = request.getPathInfo();



        //得到所有食物分类
        if(pathInfo.equals("/getType")){
            List<Type> mealbr = typeDao.getTypeByMeal(1);
            List<Type> meallu = typeDao.getTypeByMeal(2);
            List<Type> mealdin = typeDao.getTypeByMeal(3);
            session.setAttribute("breakType",mealbr);
            session.setAttribute("lunchType",meallu);
            session.setAttribute("dinType",mealdin);
            //初始化购物车数量
            session.setAttribute("num",carlist.size());

        }

        //根据分类得到该分类下的食物列表
        if(pathInfo.equals("/getByType")){
            String tid = request.getParameter("tid");
            int typeid = Integer.parseInt(tid);
            FoodDao foodDao = sqlSession.getMapper(FoodDao.class);
            List<Food> foods = foodDao.getFood(typeid);
            session.setAttribute("food",foods);
            response.sendRedirect(request.getContextPath() + "/food.jsp");
        }


        //请求食物详情页面
        if(pathInfo.equals("/detail")){
            String fid = request.getParameter("foodid").trim();

            FoodDao mapper = sqlSession.getMapper(FoodDao.class);
            Food fooddetail = mapper.selectByPrimaryKey(Integer.parseInt(fid));
            session.setAttribute("fooddetail",fooddetail);
            response.sendRedirect(request.getContextPath()+"/foodDetail.jsp");
        }

        //添加到购物车
        if(pathInfo.equals("/addcar")){
            String foodid = request.getParameter("foodid").trim();
            FoodDao mapper = sqlSession.getMapper(FoodDao.class);
            Food food = mapper.selectByPrimaryKey(Integer.parseInt(foodid));
            carlist.add(food);
            //更新购物车信息
            session.setAttribute("car",carlist);
            //更新购物车内商品数量
            session.setAttribute("num",carlist.size());
            response.sendRedirect(request.getContextPath()+"/car.jsp");
        }

        //支付请求
        if(pathInfo.equals("/pay")){
            //引入服务类
            OrderService orderService=new OrderServiceImpl();
            //拿到用户ID
            User userDetail = (User) session.getAttribute("userDetail");
            Integer uid = userDetail.getId();

            //拿到总付款金额
            String tprice = request.getParameter("tprice");
            double v = Double.parseDouble(tprice);

            //得到购物车里的ID以及每个ID对应的产品数量
            String[] values = request.getParameterValues("foodid-num");
            System.out.println(values);

            //将数据转为map的形式
            HashMap<Integer,Integer> map = new HashMap<Integer,Integer>();

            if(values.length==1){
                String value = values[0];
                String[] split = value.split(":");
                int fid = Integer.parseInt(split[0]);
                int fnum = Integer.parseInt(split[1]);
                map.put(fid,fnum);
            }else {
                for(String str:values){
                    String[] split = str.split(":");
                    int fid = Integer.parseInt(split[0]);
                    int fnum = Integer.parseInt(split[1]);
                    map.put(fid,fnum);
                }
            }

            //新建一个容器，用来保存下单的商品ID
            List<Integer> fids = new ArrayList<>();

            //将已经付款的商品清出购物车。。。。
            for(Integer foodID:map.keySet()){
                fids.add(foodID);
            }
            for(int i=0;i<carlist.size();i++){
                Integer fid = carlist.get(i).getId();
                if(fids.contains(fid)){
                    carlist.remove(i);
                }
            }
            //更新购物车信息
            session.setAttribute("car",carlist);
            //更新购物车的数量
            session.setAttribute("num",carlist.size());

            //服务类生成订单和订单详情
            orderService.addOrder(uid,map,v);

            //走请求用户订单的servlet
            response.sendRedirect(request.getContextPath() + "/order/getUserOrder");
        }


    }
}
